/*************************************************************************
 * File Name:    Binary_Tree_Preorder_Traversal.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/18 13:55:19
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Binary Tree Preorder Traversal
 |
 | Given a binary tree, return the preorder traversal of its nodes' values.
 |
 | For example:
 | Given binary tree {1,#,2,3},
 | 1
 |  \
 |   2
 |  /
 | 3
 | return [1,2,3].
 |
 | Note: Recursive solution is trivial, could you do it iteratively?
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode *root)
    {
        if (root == NULL) return vector<int>();
        
        stack<TreeNode*> s;
        vector<int> ans;
        
        TreeNode *p;
        for (p = root; p != NULL; p = p->left) {
            ans.push_back(p->val);
            s.push(p);
        }
        
        while (!s.empty()) {
            while (!s.empty() && s.top()->right == NULL) {
                s.pop();
            }
            if (s.empty()) break;
            for (p = s.top()->right, s.pop(); p != NULL; p = p->left) {
                ans.push_back(p->val);
                s.push(p);
            }
        }
        return ans;
    }
};

